package com.kgo.eidtor.controller;

import com.google.gson.Gson;

import com.kgo.eidtor.entity.KgoDocuments;
import com.kgo.eidtor.service.DocumentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author keepgoon
 * @Description: TODO
 * @date 2019/1/2611:53
 */
@RestController
@CrossOrigin
public class DocumentsController {
    @Resource
    private DocumentService documentService;
    private Gson _gs = new Gson();
    private Logger log = LoggerFactory.getLogger(DocumentsController.class);
    private StringBuffer htmlHead = new StringBuffer();

    private void htmltopdf(String html){
        htmlHead.setLength(0);
        htmlHead.append("<!DOCTYPE html>");
        htmlHead.append("<html>");
        htmlHead.append("<head>");
        htmlHead.append("<meta charset=\"utf-8\">");
        htmlHead.append("<link rel=\"stylesheet\" href=\"static/editor.css\" />");

        htmlHead.append("<title>A4</title>");
        htmlHead.append("</head>");
        htmlHead.append("<body>");
        htmlHead.append(html);
        htmlHead.append("</body>");
        htmlHead.append("</html>");

    }
    @RequestMapping(value = "/document" ,method = RequestMethod.GET,produces="text/plain;charset=UTF-8")
    public String getDocument(String id){
        KgoDocuments thisDocument  = documentService.getDocument(id);

        String html = thisDocument.getTextContent();
        htmltopdf(html);
        thisDocument.setTextContent(htmlHead.toString());
        String documentstr = _gs.toJson(thisDocument);
        log.info(documentstr);
        return documentstr;
    }
    @RequestMapping(value = "/document" ,method = RequestMethod.POST,produces="text/plain;charset=UTF-8")
    public String saveDocument(KgoDocuments document){
        int count = documentService.addDocument(document);
        Map<String,Object> outResult = new HashMap <>();
        outResult.put("count",count);
        return _gs.toJson(outResult);
    }
}
